package com.accenture.automation.biz.service;

import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.accenture.automation.common.ApiClientUtil;
import com.accenture.automation.common.CommonConstants;
import com.accenture.automation.common.bean.ApiResultBaseBean;
import com.alibaba.fastjson.JSONObject;

public class InterfaceRequestService {

	private static final Logger log = LoggerFactory.getLogger(InterfaceRequestService.class);

	private static final int apiSuccessIteCode = 200;

	public static String accountPost(String sendUrl, String param, int retryCount) {
		String jsonString = null;
		for (int i = 0; i < retryCount; i++) {
			try {
				ApiClientUtil httpClicent = new ApiClientUtil(sendUrl);
				jsonString = httpClicent.post(param);
				if (jsonString != null) {
					break;
				}
			} catch (Exception e) {
				jsonString = e.getMessage();
			}
		}
		return jsonString;
	}

	public static String accountDoePost(String sendUrl, String param, int retryCount, String token) {
		String jsonString = null;
		for (int i = 0; i < retryCount; i++) {
			try {
				ApiClientUtil httpClicent = new ApiClientUtil(sendUrl);
				httpClicent.addHeader(new BasicHeader("token", token));
				jsonString = httpClicent.post(param);
				if (jsonString != null) {
					break;
				}
			} catch (Exception e) {
				jsonString = e.getMessage();
			}
		}
		return jsonString;
	}

	public static void postITE(String sendUrl, String param, int retryCount) {
		for (int i = 0; i < retryCount; i++) {
			try {
				String jsonString = null;
				ApiClientUtil httpClicent = new ApiClientUtil(sendUrl);
				jsonString = httpClicent.post(param);
				ApiResultBaseBean apiResultBaseBean = JSONObject.parseObject(jsonString, ApiResultBaseBean.class);
				if (apiResultBaseBean.getApiCode() == apiSuccessIteCode) {
					log.debug("[result]:SUCCESS");
					break;
				} else {
					// 循环最后一次打印失败日志
					if (retryCount == i + 1) {
						log.error("[result]:" + jsonString + "[SendUrl]:" + sendUrl + "[post]:" + param);
					}

				}
			} catch (Exception e) {
				// 循环最后一次打印异常
				if (retryCount == i + 1) {
					log.error("[error]:" + e.getMessage() + "[SendUrl]:" + sendUrl + "[post]:" + param);
				}

			}
		}
	}

	public static String urlFormat(String sendUrl, String businessKey) {
		if (!businessKey.equals(CommonConstants.KAFKAKEY)) {
			sendUrl = sendUrl.replace("{accountPostPK}", businessKey);
		}
		return sendUrl;

	}

}
